package com.hhjxmedical.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EnhancedImageDownloader {

    // 添加User-Agent模拟浏览器访问
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";

    public static void main(String[] args) {
        // 定义要读取的网页文件路径、要保存的图片路径、开始索引
        String htmlFilePath = "aa.html";
        String outputDir = "d:/downloaded_01";
        int startIndex = 1;

        try {
            downloadImages(htmlFilePath, outputDir, startIndex);
            System.out.println("图片下载完成！");
        } catch (Exception e) {
            System.err.println("下载过程中出现错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void downloadImages(String htmlFilePath, String outputDir, int startIndex) throws IOException {
        // 创建输出目录
        Files.createDirectories(Paths.get(outputDir));

        // 读取HTML文件内容
        String htmlContent = new String(Files.readAllBytes(Paths.get(htmlFilePath)));

        // 使用改进的正则表达式提取图片URL
        List<String> imageUrls = extractImageUrls(htmlContent);

        System.out.println("找到 " + imageUrls.size() + " 张图片");

        int currentIndex = startIndex;
        int successCount = 0;
        int failCount = 0;

        for (String imgUrl : imageUrls) {
            try {
                // 生成文件名，根据URL扩展名确定文件类型
                String fileExtension = getFileExtension(imgUrl);
                String fileName = String.format("%04d%s", currentIndex, fileExtension);
                String filePath = outputDir + File.separator + fileName;

                System.out.print("正在下载 (" + currentIndex + "/" + imageUrls.size() + "): " + imgUrl);

                // 下载图片
                if (downloadImageWithRetry(imgUrl, filePath)) {
                    System.out.println(" - 成功");
                    successCount++;
                } else {
                    System.out.println(" - 失败");
                    failCount++;
                }

                currentIndex++;

                // 添加延迟，避免请求过快被限制
                Thread.sleep(200);

            } catch (Exception e) {
                System.err.println("下载失败: " + imgUrl + " - " + e.getMessage());
                failCount++;
            }
        }

        System.out.println("\n下载完成统计:");
        System.out.println("总图片数: " + imageUrls.size());
        System.out.println("成功下载: " + successCount);
        System.out.println("下载失败: " + failCount);
    }

    private static List<String> extractImageUrls(String htmlContent) {
        List<String> urls = new ArrayList<>();

        // 改进的正则表达式，匹配更多情况
        String[] patterns = {
                "src\\s*=\\s*['\"]([^'\"]+\\.(jpg|jpeg|png|gif|webp|bmp))[^'\"]*['\"]",
                "src\\s*=\\s*['\"]([^'\"]*www\\.imgccc\\.com[^'\"]*)[^'\"]*['\"]",
                "src\\s*=\\s*['\"]([^'\"]*)[^'\"]*['\"]"
        };

        for (String patternStr : patterns) {
            Pattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(htmlContent);

            while (matcher.find()) {
                String url = matcher.group(1);
                if (isValidImageUrl(url)) {
                    // 确保URL完整
                    String fullUrl = ensureFullUrl(url);
                    if (!urls.contains(fullUrl)) {
                        urls.add(fullUrl);
                    }
                }
            }
        }

        return urls;
    }

    private static boolean isValidImageUrl(String url) {
        if (url == null || url.trim().isEmpty()) {
            return false;
        }

        // 检查是否包含目标域名
        if (!url.contains("imgccc.com")) {
            return false;
        }

        return true;
    }

    private static String ensureFullUrl(String url) {
        if (url.startsWith("http")) {
            return url;
        } else if (url.startsWith("//")) {
            return "https:" + url;
        } else {
            return "https://" + url.replaceAll("^/+", "");
        }
    }

    private static String getFileExtension(String url) {
        if (url.toLowerCase().contains(".jpg") || url.toLowerCase().contains(".jpeg")) {
            return ".jpg";
        } else if (url.toLowerCase().contains(".png")) {
            return ".png";
        } else if (url.toLowerCase().contains(".gif")) {
            return ".gif";
        } else if (url.toLowerCase().contains(".webp")) {
            return ".webp";
        } else {
            return ".jpg"; // 默认使用jpg
        }
    }

    private static boolean downloadImageWithRetry(String imageUrl, String filePath) {
        int maxRetries = 3;

        for (int attempt = 1; attempt <= maxRetries; attempt++) {
            try {
                if (downloadImage(imageUrl, filePath)) {
                    return true;
                }

                if (attempt < maxRetries) {
                    System.out.print(" - 重试(" + attempt + "/" + maxRetries + ")");
                    Thread.sleep(1000 * attempt); // 递增延迟
                }
            } catch (Exception e) {
                if (attempt == maxRetries) {
                    System.err.println("最终失败: " + e.getMessage());
                }
            }
        }

        return false;
    }

    private static boolean downloadImage(String imageUrl, String filePath) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agent", USER_AGENT);
            connection.setConnectTimeout(30000); // 30秒连接超时
            connection.setReadTimeout(30000);    // 30秒读取超时

            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                System.err.print(" - HTTP错误: " + responseCode);
                return false;
            }

            try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
                 FileOutputStream out = new FileOutputStream(filePath)) {

                byte[] buffer = new byte[8192]; // 更大的缓冲区
                int bytesRead;
                long totalBytes = 0;

                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                    totalBytes += bytesRead;
                }

                // 检查文件大小，避免下载到空文件或错误页面
                if (totalBytes < 1024) { // 小于1KB可能是错误页面
                    System.err.print(" - 文件过小: " + totalBytes + " bytes");
                    new File(filePath).delete(); // 删除无效文件
                    return false;
                }

                return true;
            }
        } catch (Exception e) {
            System.err.print(" - 网络错误: " + e.getMessage());
            return false;
        }
    }
}